package com.mobinters.cafeman.module;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.mobinters.cafeman.CMUtils;
import com.mobinters.cafeman.R;

import com.mobinters.cafeman.CMActivity;
import com.mobinters.cafeman.adapter.ProductAdapter;
import com.mobinters.cafeman.object.Product;
import com.mobinters.parser.JSONParser;

import android.text.Editable;
import android.text.TextWatcher;
import com.mobinters.cafeman.database.DatabaseHandler;

public class MealLoadModule implements OnClickListener{
	
	CMActivity mActivity;
	ProgressBar mProgressBar;
	ImageButton mBtnRefresh;
	public static List<Product> ProductList = new ArrayList<Product>();
	ListView mListView;
	EditText txtSerch;
	ProductAdapter mAdapter;
	JSONParser mParser;
	DatabaseHandler mDatabase;
	SharedPreferences mPref;
	Editor mEditor;
	
	public MealLoadModule(CMActivity activity){
		mActivity = activity;
		
		mPref = mActivity.getSharedPreferences(CMUtils.PREF_NAME , 0);
		mEditor = mPref.edit();
		
		mParser = new JSONParser();
		
		mBtnRefresh=(ImageButton)mActivity.findViewById(R.id.btn_main_refresh);
		mBtnRefresh.setOnClickListener(this);
		mProgressBar=(ProgressBar)mActivity.findViewById(R.id.progressBar);
		mProgressBar.setVisibility(View.INVISIBLE);
		
		mListView=(ListView)mActivity.findViewById(R.id.lv_main);
		new AsyncLoad().execute(CMUtils.URL_BASE_CAFEMAN);
		
		
		
		mDatabase = new DatabaseHandler(mActivity);
		mDatabase.createProductTable();
		
		txtSerch = (EditText)mActivity.findViewById(R.id.txt_main_search);
		txtSerch.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				String searchText = txtSerch.getText().toString();
				if(mAdapter!=null){
					boolean result = mAdapter.filter(searchText);
					if(result) mListView.setVisibility(View.VISIBLE);
					else mListView.setVisibility(View.INVISIBLE);
				}
			}
		});
	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int id = v.getId();
		switch(id){				
		case R.id.btn_main_refresh:
			new AsyncLoad().execute(CMUtils.URL_BASE_CAFEMAN);
		break;
		
		}
	}
	
	class AsyncLoad extends AsyncTask<String,Void,Void>{

		@Override
		protected Void doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			loadListBackground(arg0[0]);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			showProgressBar(false);
			showListView();
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			showProgressBar(true);
		}
		
	}
	
	private void showListView(){
		ProductList = mDatabase.getAllProduct();
		
		
		if(ProductList!=null){
			mAdapter=new ProductAdapter(mActivity, ProductList);
			//mActivity.OrderList = mAdapter.mFullData;
			
			mListView.setAdapter(mAdapter);
		
		}
	}
	
	
	private void loadListBackground(String xURL){
		//String fullURL = xURL + "?username=" + CMUtils.USER_NAME_TEST +"&" + "password="+ CMUtils.USER_PSW_TEST;
		String fullURL = xURL + "?username=" + mPref.getString(CMUtils.PREF_KEY_USERNAME, "waiter") +"&" + 
							"password="+ mPref.getString(CMUtils.PREF_KEY_PASSWORD, "123456");
		JSONObject jObj = mParser.getJSONFromGET(fullURL);
		
		//String content=Utils.getStringFromAsset(mActivity, "list.txt");
		if(jObj!=null){
			Log.e("jObj",jObj.toString());
			try {
					String status = jObj.getString("status");
					if(status == null || status.compareTo("ok")!=0){
						ProductList = null;
						return;
					}
					//else : return status = ok
					ProductList=new ArrayList<Product>();
					
					JSONArray jList = jObj.getJSONArray("content");
					
					JSONObject jItem;
					Product item;
					
					for(int i = 0;i<jList.length();i++){
						jItem = jList.getJSONObject(i);
						item = new Product();
						item.ProductId = i*100 + 1;
						item.ProductCategory = jItem.getString("category");
						item.ProductName1 = jItem.getString("name1");
						item.ProductName2 = jItem.getString("name2");
						item.ProductName3 = jItem.getString("name3");
						
						item.IconUrl =  CMUtils.URL_BASE + jItem.getString("image");
						item.Description = jItem.getString("description");
						item.ProductPrice  = jItem.getDouble("cost");  
						
						//mList.add(item);
						mDatabase.addProduct(item);
					}
				 
			
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				//mList=null;
			}
			
		}
	}
	
	

	private void showProgressBar(boolean show){
		if(show){
			mBtnRefresh.setVisibility(View.INVISIBLE);
			mProgressBar.setVisibility(View.VISIBLE);
		}
		else{
			mBtnRefresh.setVisibility(View.VISIBLE);
			mProgressBar.setVisibility(View.INVISIBLE);
		}
	}
	
	
}
